/*
 * 上海远境文化传媒有限公司 版权所有
 */
package controllers.api.v1;

import cache.CacheHelper;
import controllers.api.v1.auth.ApiAuth;
import controllers.license.LicenseChecker;
import ext.Func;
import ext.auth.CheckUserRole;
import facade.AppContext;
import facade.base.AdminUserFacade;
import facade.base.CorpFacade;
import facade.open.BaseJsonAPI;
import facade.open.request.CorpRequest;
import facade.open.response.AdminUserResponse;
import facade.open.response.CorpResponse;
import helper.GlobalConfigKeys;
import helper.constants.CacheName;
import models.base.AdminUser;
import models.base.Corp;
import models.base.DiffHistory;
import models.enums.UserRole;
import org.apache.commons.lang.StringUtils;
import play.i18n.Messages;
import play.mvc.With;

import java.util.*;

import static java.util.stream.Collectors.toList;
import static util.common.ArrayHelper.safeSplit;

/**
 * 公司接口.
 */
@With({ApiAuth.class, LicenseChecker.class})
public class CorpsAPI extends BaseJsonAPI {

    public static void show() {
        AdminUser user = AppContext.currentUser();
        Corp corp = AppContext.currentCorp();
        if (corp != null) {
            CorpResponse corpResponse = getCorpResponse(user, corp);

            renderData(corpResponse);
        }

        renderFailMessage("无公司数据");
    }

    private static CorpResponse getCorpResponse(AdminUser user, Corp corp) {
        CorpResponse corpResponse = CorpFacade.getCorpResponse(corp, user);
        List<AdminUser> adminForCorp = AdminUser.findAdminForCorp(corp, 3);
        if (adminForCorp != null && adminForCorp.size() > 0) {
            corpResponse.admins = adminForCorp.stream().map(AdminUserResponse::fromSimple).collect(toList());
        }
        return corpResponse;
    }

    /**
     * 保存修改.
     * <p>
     * 注意: 不要改成用 Corp对象的形式, 用户可能可以攻击修改一些不应修改的属性, 如付费信息.
     */
    @CheckUserRole("SuperAdmin")
    public static void update() {
        Corp corp = AppContext.currentCorp();

        CorpRequest corpRequest = validateRequestBody("corpForm", CorpRequest.class);

        DiffHistory.storePrevObject(corp, new Corp());

        // 私有安装版本不能修改公司名.
        if ((corp.hasFunc(Func.FREEZE_CORPNAME) || CorpFacade.isPrivateInstallVersion()) && !corpRequest.name.equals(corp.name)) {
            flash.put("warn", Messages.get("flash.company.warn.edu-cannot-change-name"));
        } else {
            corp.name = corpRequest.name;
        }

        if (StringUtils.isNotEmpty(corpRequest.notice)) {
            corp.notice = corpRequest.notice;
        }
        if (StringUtils.isNotEmpty(corpRequest.emailPostfix)) {
            corp.emailPostfix = corpRequest.emailPostfix.toLowerCase();
        } else {
            corp.emailPostfix = null;
        }

        if (corpRequest.logoObject != null) {
            corp.logoObject = corpRequest.logoObject;
        }

        if (corpRequest.lang != null) {
            corp.lang = corpRequest.lang;
        }

        corp.updatedAt = new Date();
        corp.save();
        AdminUser user = AppContext.currentUser();
        DiffHistory.recordHistory(user.id, corp, user.name + "通过" + Messages.get("clientType." + AppContext.getClientType()) + "端修改");
        AdminUserFacade.cleanCache(user);

        flash.put("notice", Messages.get("flash.notice.save-success"));
        CorpResponse corpResponse = getCorpResponse(user, corp);
        renderData(corpResponse);
    }

    /**
     * 前端可使用的配置.
     */
    public static void frontConfigs() {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put(GlobalConfigKeys.WEB_ASSET_BASE, AppContext.getGlobalConfig(GlobalConfigKeys.WEB_ASSET_BASE));
        String webCustomAssets = AppContext.getGlobalConfig(GlobalConfigKeys.WEB_CUSTOM_ASSETS);
        String[] assets = new String[]{};
        if (StringUtils.isNotBlank(webCustomAssets)) {
            assets = safeSplit(webCustomAssets, ",");
        }
        result.put(GlobalConfigKeys.WEB_CUSTOM_ASSETS, assets);
        result.put(GlobalConfigKeys.WEB_CUSTOM_ASSETS + ".js", Arrays.stream(assets).filter(asset -> asset.endsWith(".js")).collect(toList()));
        result.put(GlobalConfigKeys.WEB_CUSTOM_ASSETS + ".css", Arrays.stream(assets).filter(asset -> asset.endsWith(".css")).collect(toList()));
        renderData(result);
    }

    /**
     * 刷新显示屏版本号
     */
    public static void refreshDisplay(String id) {
        if (StringUtils.isNotBlank(id)) {
            CacheHelper.delete(CacheName.DISPLAY_REFRESH_VERSION + id);
            renderSuccMessage("刷新成功:" + id);
        } else {
            Corp corp = AppContext.currentCorp();
            if (corp != null) {
                CacheHelper.delete(CacheName.DISPLAY_REFRESH_VERSION + corp.id);
            }
            if ("1".equals(params.get("all"))) {
                CacheHelper.delete(CacheName.DISPLAY_REFRESH_VERSION);
            }
        }

        renderSuccMessage("刷新成功");
    }


    /**
     * 列出子公司.
     */
    public static void listAllCorps() {
        Corp corp = AppContext.currentCorp();

        List<Corp> allCorps = Corp.findAllByRootCorp(corp);

        renderData(allCorps.stream().map(CorpResponse::from).collect(toList()));
    }
}
